/****************************************************
          File Name:52-3-client.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sun 21 Sep 2014 02:41:55 PM CST
*****************************************************/

#include"mq.h"

int main(int argc,char *argv[])
{
    if(argc<3 || strcmp(argv[1],"--help")==0)
    {
        printf("%s /mq path\n",argv[0]);
        exit(EXIT_FAILURE);
    }

    mqd_t mq;
    struct mq_attr attr;
    char *buf;
    int bytes;

    mq=mq_open(argv[1],O_RDWR);
    if(mq==(mqd_t)-1)
        err("mq_open");
    if(mq_getattr(mq,&attr)==-1)
        err("getattr");
    buf=malloc(attr.mq_msgsize);
    if(buf==NULL)
        err("malloc");
    
    if(mq_send(mq,argv[2],strlen(argv[2]),0)==-1)
        err("send path");

    for(;;)
    {
        if((bytes=mq_receive(mq,buf,attr.mq_msgsize,0))==-1)
            err("receive file contents");
        if(bytes==0)
            break;
        if(write(STDOUT_FILENO,buf,attr.mq_msgsize)==-1)
            err("write");
        memset(buf,0,attr.mq_msgsize);
    }

    exit(EXIT_SUCCESS);
}
